package Computer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import Process.Consumer;
import Process.Process;
import Process.Producer;

/**
 * SharedMemory class.
 * 
 * @author Stephen Amos, Zach Turk, Dickson Kwong
 *
 */

public class SharedMemory {

	private final static int MAXLOCATIONS = 10;
	
	// an array of addressable (indexed) locations
	private int[] values;
	// an array of addressable (indexed) semaphores
	private List<Queue<PCB>> semaphores;
	
	public SharedMemory() {
		this((int) (MAXLOCATIONS));
	}
	
	public SharedMemory(int num_locations) {
		values = new int[num_locations];
		
		// initialize the semaphores
		semaphores = new ArrayList<Queue<PCB>>();
		for (int i=0; i < values.length; i++) semaphores.add(new ArrayDeque<PCB>());
	}
	
	//call this to get in line to be semaphore owner
	public void semUp(Process p) {
		if (p instanceof Producer) {

			
		} else if (p instanceof Consumer) {
			

		}
//		} else if (p instanceof Consumer) {
//			
//		}
	}
	
	// call this to give up ownership
	public void semDown(int the_index) {
		semaphores.get(the_index).poll();
	}
	
	public Queue<PCB> getList(int the_index){
		return semaphores.get(the_index);
	}
	
	public String printMutexStatus(){
		StringBuilder the_string = new StringBuilder();
		
		for (Queue<PCB> the_queue : semaphores){
			the_string.append("[");
			if (the_queue.size() > 0){
				the_string.append("Locked");
			}
			else the_string.append("Unlocked");
			the_string.append("], ");
		}
		return the_string.toString();
	}

	public int getValue(int the_index){
		return values[the_index];
	}
	
	public void write(int index, int value) {
		values[index] = value;
	}
	
	
	
	
	/**
	 * An enum class for the Semaphore state.
	 * @author Dickson Kwong
	 */
	public enum State {
		 UP, DOWN;
		public String toString() {
			String s = super.toString();
			return s.substring(0, 1) + s.substring(1).toLowerCase();
		}
	}
}
